package com.zztl.infiniteBand.ui.fragment


import android.bluetooth.BluetoothGatt
import android.content.Context
import android.content.Intent
import android.graphics.Point
import android.net.Uri
import android.os.Handler
import android.view.View
import android.view.WindowManager
import butterknife.OnClick
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleConnectCallback
import com.clj.fastble.callback.BleDataCountCallback.BleStepCallback
import com.clj.fastble.data.BleDevice
import com.clj.fastble.exception.BleException
import com.clj.fastble.utils.BleLog

import com.zztl.infiniteBand.BraceletApplication
import com.zztl.infiniteBand.R
import com.zztl.infiniteBand.base.BaseMvpFragment
import com.zztl.infiniteBand.eventbus.*
import com.zztl.infiniteBand.model.ForceValueBean
import com.zztl.infiniteBand.model.MiningBean
import com.zztl.infiniteBand.net.requestBean.SyncStepRequest
import com.zztl.infiniteBand.presenter.MiningPresenter
import com.zztl.infiniteBand.ui.activity.AwardRuleActivity
import com.zztl.infiniteBand.ui.activity.LinkActivity
import com.zztl.infiniteBand.ui.view.Diamond
import com.zztl.infiniteBand.ui.view.DiamondView
import com.zztl.infiniteBand.ui.view.dialog.LoadingDialog
import com.zztl.infiniteBand.ui.view.mvpview.MiningView
import com.zztl.infiniteBand.util.*
import com.zztl.infiniteBand.util.device.DeviceUtil
import kotlinx.android.synthetic.main.fragment_mining_layout.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*

/**
 * @desc
 * @auth ${user}
 * @time 2018/9/13  16:05
 */
class MiningFragment : BaseMvpFragment<MiningView, MiningPresenter>(), MiningView, DiamondView.ClickListener, DiamondView.AnimatorEndListener {


    private val TAG = "bluetooth"


    lateinit var mMiningPresenter: MiningPresenter

    private val mDiamondList = ArrayList<Diamond>()

    private var mTotalSize: Int = 0
    private var mServiceList: ArrayList<MiningBean.DataBean.RowsBean>? = null  //服务器返回的水晶列表
    private val mHandler = Handler()

    var mView: View? = null
    private var mDiamond: Diamond? = null

    private var receivedCount = 0  //领取的水晶个数
    private var isFirstRequest = true //第一次请求水晶收益的标志

    private var mScreenWidth: Int = 0

    private val receiveList = ArrayList<String>()  //领取的水晶集合，有一键领取和单个领取两种


    private var isFirstSync = false  //第一次同步的标记位


    private var mLoadingDialog: LoadingDialog? = null

    private var allReceiveDiamodCount: Int = 0


    /**
     * 再次请求水晶收益的任务
     */
    private val mRequestRunnable = Runnable {
        DeviceUtil.getLastConnectMac().isNotEmpty().let {
            if (it) {
                mMiningPresenter.getMiningData(DeviceUtil.getLastConnectMac(), activity!!, false)
            }
        }

    }

    /**
     * 连接超时的任务
     */
    private val mConnectTimeoutRunnable = Runnable { dismissLoadingDialog() }


    lateinit var mRunnableList: ArrayList<Runnable>


    private val mPermissionGrant = object : PermissionUtils.PermissionGrant {
        override fun onPermissionGranted(requestCode: Int) {
            when (requestCode) {
                PermissionUtils.CODE_MULTI_PERMISSION -> try {
                    showLoadingDialog(getString(R.string.设备连接中请稍后))
//                    BraceletApplication.zhBraceletService?.connectDevice(DeviceUtil.getLastConnectMac())
                    BleManager.getInstance().connect(DeviceUtil.getLastConnectMac(), mConnectListener)
                    removeRunnable(null)
                    mHandler.postDelayed(mConnectTimeoutRunnable, 30 * 1000)
                } catch (e: Exception) {
                }
            }
        }
    }

    override fun setLayoutId(): Int = R.layout.fragment_mining_layout


    override fun initData() {

        val wm = activity!!
                .getSystemService(Context.WINDOW_SERVICE) as WindowManager
        mScreenWidth = wm.defaultDisplay.width
        mRunnableList = arrayListOf(mRequestRunnable, mConnectTimeoutRunnable)
        diamondView.setAnimatorEndListener(this)
        diamondView.setOnItemClickListener(this)

        setResumeUi()
        getForceValue(false)
        if(DeviceUtil.getLastConnectMac().isNotEmpty()){
            mMiningPresenter.getMiningData(DeviceUtil.getLastConnectMac(), activity!!, isFirstRequest)
            isFirstRequest=false
        }
        EventBus.getDefault().register(this)
//        BraceletApplication.zhBraceletService?.addConnectorListener(mConnectListener)


    }

    private fun getForceValue(isfirst: Boolean) {
        mMiningPresenter.getForceValue(isfirst, activity!!)
    }


    //蓝夜连接的回调
    private val mConnectListener = object : BleConnectCallback() {
        override fun onStartConnect() {
        }

        override fun onConnectFail(bleDevice: BleDevice?, exception: BleException?) {
            activity?.runOnUiThread {
                dismissLoadingDialog()
                setUibyConnecet(false)
            }
        }

        override fun onConnectSuccess(bleDevice: BleDevice?, gatt: BluetoothGatt?, status: Int) {
            activity?.runOnUiThread(object : Runnable {
                override fun run() {
                    dismissLoadingDialog()
                    setUibyConnecet(true)
                    DeviceUtil.getLastConnectMac().isNotEmpty().let {
                        if (it) {
                            mMiningPresenter.getMiningData(DeviceUtil.getLastConnectMac(), activity!!, isFirstRequest)
                            if (isFirstRequest) {
                                isFirstRequest = false
                            }
                        }
                    }
                }
            })
        }

        override fun onDisConnected(isActiveDisConnected: Boolean, device: BleDevice?, gatt: BluetoothGatt?, status: Int) {
            activity?.runOnUiThread(object : Runnable {
                override fun run() {
                    syncStep(BraceletApplication.watchCountStep)
                    EventBus.getDefault().post(ConnectedEvent(false))
                    dismissLoadingDialog()
                    setUibyConnecet(false)
                }
            })
        }

    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Evnent(event: ConnectedEvent) {
        setUibyConnecet(event.isConnected)
    }




    @Subscribe(threadMode = ThreadMode.MAIN)
    fun Evnent(event: UpdateForceVlueEvent) {
        getForceValue(false)
    }

    private fun setUibyConnecet(connected: Boolean) {
        if (null != btn_sync) {
            btn_sync.isClickable = true
            if (!connected) {
                tv_watch_name.text = getString(R.string.未连接设备)
                ivConnectState.setImageResource(R.mipmap.sbiao_sy)

                btn_sync.text = if (DeviceUtil.getLastConnectMac().isEmpty()) getString(R.string.绑定设备) else getString(R.string.连接设备)
                tv_bottom_hint.text = getString(R.string.绑定手表获取更高收益)
            } else {
                tv_bottom_hint.text = getString(R.string.同步步数获取更高收益)
                tv_watch_name.text = DeviceUtil.DEVICE_NAME
                btn_sync.text = getString(R.string.同步数据)
                ivConnectState.setImageResource(R.mipmap.sbiao_jihuo)
            }
        }
    }


    override fun createPresenter(): MiningPresenter {
        mMiningPresenter = MiningPresenter()
        return mMiningPresenter
    }


    /**
     * 获取设备收益成功的回调
     *
     * @param bean
     */
    override fun miningSuccess(bean: MiningBean) {
        receivedCount = 0
        mServiceList = bean.data!!.rows as ArrayList<MiningBean.DataBean.RowsBean>?
        mTotalSize = bean.data!!.total
        tv_produce.visibility = if (mTotalSize == 0) View.VISIBLE else View.GONE
        btn_all_receive.visibility=if(mTotalSize==0) View.GONE else View.VISIBLE
        setDiamondData(mServiceList!!)
        //        }
    }


    /**
     * 添加水晶数据
     *
     * @param diamondList
     */
    private fun setDiamondData(diamondList: MutableList<MiningBean.DataBean.RowsBean>) {
        LogUtils.i("swl", "水晶个数-------------" + diamondList.size)
        mDiamondList.clear()
        val size = if (diamondList.size > 10) 10 else diamondList.size
        for (i in 0 until size) {
            diamondList[i].let {
                mDiamondList.add(Diamond(it.settlementMoney, it.equipmentMileageSettlementId!!, "true" == it.yesterdayStatus, true))
            }

        }

        //不断移除服务器的水晶数
        if (diamondList.size > 10) {
            for (i in 0..9) {
                diamondList.removeAt(0)
            }
        } else {
            diamondList.clear()
        }
        diamondView.setWaters(mDiamondList)
    }


    /**
     * 点击水晶
     *
     * @param view
     */
    override fun clickItem(view: View) {
        val tag = view.tag
        if (tag is Diamond) {
            receiveDiamond(view, tag)
        }
    }


    /**
     * 收取水晶
     *
     * @param view
     * @param diamond
     */

    private fun receiveDiamond(view: View, diamond: Diamond) {
        mView = view
        this.mDiamond = diamond
        if (mDiamond!!.isFirstClick) {
            receiveList.clear()
            receiveList.add(diamond.equipmentMileageSettlementId)
            mDiamond!!.isFirstClick = false
            view.tag = mDiamond
            mMiningPresenter.receiveAward(receiveList, false, activity!!)
        }
    }


    /**
     * 收取单个水晶成功
     */
    override fun receiveSuccess() {
        try {
            PlayVoice.playVoice(activity!!)
        } catch (e: Exception) {
        }
        receivedCount++
        diamondView.animRemoveView(mView, Point(mScreenWidth / 2, rl_robot_bg.measuredHeight))
    }

    override fun receiveFail() {
        btn_all_receive.isClickable = true
        if (null != mDiamond && null != mView) {
            mDiamond!!.isFirstClick = true
            mView!!.tag = mDiamond
        }
    }


    /**
     * 一键收取水晶成功
     */
    override fun receiveAllSuccess() {
        btn_all_receive.isClickable = true
        try {
            PlayVoice.playVoice(activity!!)
        } catch (e: Exception) {
        }

        receivedCount += receiveList.size
        allReceiveDiamodCount = 0
        for (i in 0 until diamondView.viewsSize) {
            allReceiveDiamodCount++
            diamondView.animRemoveView(diamondView.views[i], Point(mScreenWidth / 2, rl_robot_bg.getMeasuredHeight()))
        }

    }


    /**
     * 收取水晶的动画结束回调
     */
    override fun endEnimator(view: View?) {
        diamondView.views.remove(view)
        if (receiveList.size == 1) {
            btn_all_receive.setClickable(true)
        }
        if (diamondView.viewsSize === 0) {
            if (receiveList.size == 1) {
                checkHasDiamond()
            } else {
                if (allReceiveDiamodCount == receiveList.size) {
                    checkHasDiamond()
                }
            }
        }
    }

    /**
     * 完成添加水晶的回调
     */
    override fun finishAddView() {
        btn_all_receive.isClickable = true
    }

    /**
     * 获取原力值成功的回调
     */
    override fun getFroceValueSuccess(bean: ForceValueBean) {
        btn_invite.text = getString(R.string.原力值) + bean.data!!.forceValue
    }


    /**
     * 每领完一次水晶判断是否还有剩余水晶，规避钱包问题导致领取不成功
     */
    private fun checkHasDiamond() {
        if (diamondView != null && mServiceList!!.size > 0 && receivedCount < mTotalSize) {
            setDiamondData(mServiceList!!)
            return
        }
        if (receivedCount == mTotalSize) {
//            removeRunnable(null)
            mHandler.postDelayed(mRequestRunnable, 1000)
//            mMiningPresenter.getMiningData(imei, activity!!, false)
        }
    }


    /**
     * 每次resume时 刷新界面
     */
    fun setResumeUi() {
        btn_sync.isClickable = true
        BleManager.getInstance().isConnected.let {
            setUibyConnecet(it)
        }
        isFirstSync = false
    }


    @OnClick(R.id.btn_sync, R.id.btn_rule, R.id.btn_invite, R.id.btn_all_receive)
    fun click(view: View) {
        when (view.id) {
            R.id.btn_sync -> {
                if (getString(R.string.绑定设备).equals(btn_sync.text.toString())) {
                    showActivity(LinkActivity::class.java)
                } else {
                    BleManager.getInstance().isConnected?.let {
                        if (it) {

                            if (it) {
                                false
                                LogUtils.i("swl", "同步步数---------------")
                                showLoadingDialog(getString(R.string.同步数据中))
                                isFirstSync = true
                                BleManager.getInstance().dataComonent.getActivityCount { snNumber ->
                                    BleManager.getInstance().dataComonent.getStep(snNumber, 0, object : BleStepCallback {
                                        override fun getOneceStep(step: Int) {
                                            BleLog.i("---step-----------" + step)
                                        }

                                        override fun getStep(step: Int) {
                                            EventBus.getDefault().post(WatchStepEvent(step))
//                                                syncedStep = step
                                            syncStep(step)
                                        }
                                    })
                                    /* BleManager.getInstance().dataComonent.getHeartRate(snNumber) {

                                     }*/
                                }
                                btn_sync.isClickable = false


                            }


                        } else {
                            if (!DeviceUtil.bluetoothIsEnabel()) {
                                DeviceUtil.showturnOnBlutoothAlertView(activity!!)
                            } else {
//                                BraceletApplication.zhBraceletService?.connectDevice(DeviceUtil.getLastConnectMac())
                                PermissionUtils.requestMultiPermissions(activity!!, mPermissionGrant, PermissionUtils.CODE_INIT_PERMISSION)

                            }
                        }
                    }
                }
            }
            R.id.btn_rule -> openUrl("http://ifr.life/burn-to-earn-programme/")//showActivity(AwardRuleActivity::class.java)

            R.id.btn_all_receive -> {
                receiveList.clear()
                if (diamondView.viewsSize == 0) {
                    return
                }
                btn_all_receive.isClickable = false
                for (i in 0 until diamondView.viewsSize) {
                    val child = diamondView.views[i]
                    val diamond = child.tag as Diamond
                    receiveList.add(diamond.equipmentMileageSettlementId)
                }
                mMiningPresenter.receiveAward(receiveList, true, activity!!)
            }
        }
    }


    private fun dismissLoadingDialog() {
        mLoadingDialog?.let {
            if (it.isShowing) {
                it.dismiss()
            }
        }

    }


    private fun showLoadingDialog(content: String) {

        mLoadingDialog?.run {
            null
        }
        mLoadingDialog = LoadingDialog.Builder(activity!!)
                .setShowMessage(true)
                .setMessage(content)
                .setCancelable(true).create()
        mLoadingDialog!!.show()
    }


    /**
     * 同步步数
     *
     * @param step
     */
    private fun syncStep(step: Int) {
        activity?.runOnUiThread {

            if (step > 0) {

                    mMiningPresenter.syncStep(SyncStepRequest(BleManager.getInstance().connecredDevice.mac, step), activity!!)

            } else {
                if (isFirstSync) {
                    dismissLoadingDialog()
                    isFirstSync = false
                    activity!!.toast(getString(R.string.步数为0))
                }
            }
        }

    }

    /**
     * 手动同步数据的回调
     */

    override fun syncStepSuccess(b: Boolean, mileageSum: Int) {
        if (isFirstSync) {
            dismissLoadingDialog()
            if (b) {
                activity!!.toast(getString(R.string.同步成功))
                btn_sync.text = getString(R.string.同步成功)
                isFirstSync = false
                EventBus.getDefault().post(SyncStepCount(mileageSum))
            } else {
                btn_sync.isClickable = true
                activity?.toast(getString(R.string.同步失败))
            }
        }
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
                                            grantResults: IntArray) {
        PermissionUtils.requestPermissionsResult(activity, requestCode, permissions, grantResults, mPermissionGrant)
    }


    override fun onPause() {
        isFirstSync = false
        super.onPause()
    }


    fun removeRunnable(runnable: Runnable?) {

        for (run in mRunnableList) {
            if (runnable == null || run != runnable) {
                mHandler.removeCallbacks(run)
            }
        }

    }

   /* public void onClick(View view) {
        Intent intent = new Intent();
        intent.setData(Uri.parse(URL));//Url 就是你要打开的网址
        intent.setAction(Intent.ACTION_VIEW);
        this.startActivity(intent); //启动浏览器
    }
    */
    private fun openUrl(url:String){
       Intent().run {
           data = Uri.parse(url)
           action = Intent.ACTION_VIEW
           startActivity(this) //启动浏览器
       }
   }


    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        removeRunnable(null)
        dismissLoadingDialog()
        /*       BraceletApplication.zhBraceletService?.removeSimplePerformerListenerLis(mPerformerListener)
               BraceletApplication.zhBraceletService?.removeConnectorListener(mConnectListener)*/
        super.onDestroy()
    }
}
